<template>
  <div id="home">
    <Header :user_img="userImg" />

    <van-tabs v-model="active" color="skyblue" swipeable sticky animated>
      <van-tab
        v-for="(item,index) in tabs"
        :title="item.title"
        :key="index"
        class="tab"
        title-style="font-size:3.889vw"
      >
        <van-list
          v-model="item.loading"
          :finished="item.finished"
          finished-text="我也是有底线的!!!"
          @load="onLoad"
          :immediate-check="false"
        >
          <div class="articlesParent">
            <ArticleCover
              :article="article"
              v-for="(article,index) in item.list"
              :key="index"
            />
          </div>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import Header from "@/components/common/Header.vue";
import ArticleCover from "@/components/home/ArticleCover.vue";

export default {
  components: {
    Header,
    ArticleCover,
  },
  data() {
    return {
      userImg: "",
      active: 0,
      tabs: [],
    };
  },
  created() {
    // 获取用户头像
    this.getUserImg();
    // 获取Tab分类标签
    this.getTabs();
  },
  methods: {
    async getUserImg() {
      // 判断是否登录来获去用户头像
      if (localStorage.getItem("id")&& localStorage.getItem("token")) {
        let res = await this.$http.get(`/user/${localStorage.getItem("id")}`);
        this.userImg = res.data[0].user_img;
      }
    },
    async getTabs() {
      let res = await this.$http.get("/category");
      // 封装tabs
      this.tabs = this.changeTabs(res.data);
      // 获取所选择Tab标签的内容
      this.getContent();
    },
    changeTabs(data) {
      let Tabs = data.map((item) => {
        // 增加list来放置该分类的子类容,page保存当前分类加载页数，finished保存当前分类是否加载完毕
        item.list = [];
        item.page = 0;
        item.loading = false;
        item.finished = false;
        return item;
      });
      return Tabs;
    },
    async getContent() { // 获取所选择Tab标签的内容
      let Id = this.tabs[this.active]._id;
      let Page = this.tabs[this.active].page;
      let Pagesize = 10
      let res = await this.$http.get(`/detail/${Id}`, {
        params: {
          page: Page,
          pagesize: Pagesize,
        },
      });
      // 将获取的内容添加到对应tab
      this.tabs[this.active].list.push(...res.data);
      // 暂停上滑加载
      this.tabs[this.active].loading = false;
      // 判断最后一页，终止上滑加载
      if (res.data.length < Pagesize) {
        this.tabs[this.active].finished = true;
      }
    },
    async onLoad(){
      setTimeout(()=>{
        // 当前分类加载页数 +1
        this.tabs[this.active].page += 1;
        this.getContent()
      },500)
    }
  },
  watch: {
    active() {
      if (this.tabs[this.active].finished === true) {
        return
      }
      this.getContent();
    },
  },
};
</script>

<style lang="less" scoped>
#home {
  .articlesParent {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }
}
</style>
